import 'package:flutter/material.dart';
import 'package:flutter_buisiness_2006a/bean/category_goods_list_bean_result.dart';
import 'package:flutter_buisiness_2006a/bean/category_parent_bean_result.dart';
import 'package:flutter_buisiness_2006a/provider/category_provider.dart';
import 'package:flutter_buisiness_2006a/provider/detail_info_provider.dart';
import 'package:flutter_buisiness_2006a/router/application.dart';
import 'package:flutter_buisiness_2006a/service/service_method.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

class CategoryPage extends StatefulWidget {
  const CategoryPage({Key? key}) : super(key: key);

  @override
  State<CategoryPage> createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  //一级列表分类的数据源
  List<CategoryParentBean?>? parentList = [];

  bool isFirst = true;

  //请求一级分类列表的方法
  Future _getCategoryParent() async {
    await request('categoryParent', null).then(
        (value) => parentList = CategoryParentBeanResult.fromJson(value).data);
    if (isFirst) {
      Provider.of<CategoryProvider>(context, listen: false)
          .setChildCategoryList(parentList![0]!.data);
      _getCategoryGoodsList(parentList![0]!.data![0]!.id, 1, 10, context);
      isFirst = false;
    }
    return parentList;
  }

  //请求三级列表的方法
  void _getCategoryGoodsList(id, page, size, context) {
    var formData = {'category_id': id, 'currentPage': page, 'pageSize': size};
    request('categoryGoodsList', formData).then((value) {
      Provider.of<CategoryProvider>(context, listen: false)
          .setCategoryGoodsList(
              CategoryGoodsListBeanResult.fromJson(value).data);
    });
  }

  //一级列表的item
  Widget _leftInkWell(index) {
    bool isClick = false;
    isClick = (index == Provider.of<CategoryProvider>(context).parentIndex)
        ? true
        : false;
    return InkWell(
      onTap: () {
        Provider.of<CategoryProvider>(context, listen: false)
            .setChildCategoryList(parentList![index]!.data);
        Provider.of<CategoryProvider>(context, listen: false)
            .changeParentIndex(index);
        Provider.of<CategoryProvider>(context, listen: false)
            .changeChildIndex(0);
        _getCategoryGoodsList(
            parentList! //一级列表的数据源
                    [index]! //一级列表的item
                .data! //一级列表item对应的二级列表
                    [0]! //二级列表中下标为0的item
                .id //二级列表中下标为0的item对应的三级列表需要请求的id
            ,
            1,
            10,
            context);
      },
      child: Container(
        height: ScreenUtil().setHeight(100).toDouble(),
        padding: const EdgeInsets.only(left: 15, top: 15),
        decoration: BoxDecoration(
          color: isClick ? Colors.black26 : Colors.white,
          border:
              const Border(bottom: BorderSide(width: 1, color: Colors.black12)),
        ),
        child: Text(
          parentList![index]!.category_name!,
          style: TextStyle(fontSize: ScreenUtil().setSp(28).toDouble()),
        ),
      ),
    );
  }

  //一级分类列表
  Widget _leftCategoryNav() {
    return Container(
      width: ScreenUtil().setWidth(180).toDouble(),
      decoration: const BoxDecoration(
          border: Border(right: BorderSide(width: 1, color: Colors.black12))),
      child: ListView.builder(
          itemCount: parentList!.length,
          itemBuilder: (context, index) {
            return _leftInkWell(index);
          }),
    );
  }

  @override
  void initState() {
    // request('categoryParent', null).then((value) =>
    //     print(CategoryParentBeanResult.fromJson(value).data![0]!.data!.length));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334);
    return Scaffold(
      appBar: AppBar(
        title: const Text('分类'),
      ),
      body: Row(
        children: [
          FutureBuilder(
              future: _getCategoryParent(),
              builder: (context, val) {
                if (val.hasData) {
                  return _leftCategoryNav();
                } else {
                  return const Center(
                    child: Text('加载中...'),
                  );
                }
              }),
          Column(
            children: [
              RightCategoryNav(),
              Expanded(
                child: CategoryGoodsList(),
              )
            ],
          )
        ],
      ),
    );
  }
}

//二级分类列表
class RightCategoryNav extends StatelessWidget {
  const RightCategoryNav({Key? key}) : super(key: key);

  void _getCategoryGoodsList(id, page, size, context) {
    var formData = {'category_id': id, 'currentPage': page, 'pageSize': size};
    request('categoryGoodsList', formData).then((value) {
      Provider.of<CategoryProvider>(context, listen: false)
          .setCategoryGoodsList(
              CategoryGoodsListBeanResult.fromJson(value).data);
    });
  }

  //右侧上方小导航的item
  Widget _rightInkWell(CategoryChildBean item, context, index) {
    bool isClick = false;
    isClick = (index == Provider.of<CategoryProvider>(context).childIndex)
        ? true
        : false;
    return InkWell(
      onTap: () {
        Provider.of<CategoryProvider>(context, listen: false)
            .changeChildIndex(index);
        _getCategoryGoodsList(item.id, 1, 10, context);
        Provider.of<CategoryProvider>(context, listen: false)
            .setChildId(item.id);
      },
      child: Container(
        color: isClick ? Colors.pink : Colors.white,
        padding: const EdgeInsets.fromLTRB(5, 10, 5, 10),
        child: Text(
          item.category_name!,
          style: TextStyle(fontSize: ScreenUtil().setSp(28).toDouble()),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(80).toDouble(),
      width: ScreenUtil().setWidth(570).toDouble(),
      decoration: const BoxDecoration(
          color: Colors.white,
          border: Border(bottom: BorderSide(width: 1, color: Colors.black12))),
      child: ListView.builder(
        itemCount:
            Provider.of<CategoryProvider>(context).childCategoryList.length,
        itemBuilder: (context, index) {
          return _rightInkWell(
              Provider.of<CategoryProvider>(context).childCategoryList[index],
              context,
              index);
        },
        scrollDirection: Axis.horizontal,
      ),
    );
  }
}

//三级列表
class CategoryGoodsList extends StatelessWidget {
  const CategoryGoodsList({Key? key}) : super(key: key);

  void _getCategoryGoodsList(id, page, size, context) {
    var formData = {'category_id': id, 'currentPage': page, 'pageSize': size};
    request('categoryGoodsList', formData).then((value) {
      Provider.of<CategoryProvider>(context, listen: false)
          .addCategoryGoodsList(
              CategoryGoodsListBeanResult.fromJson(value).data);
    });
  }

  //商品图片
  Widget _goodsImage(index, context) {
    return SizedBox(
      width: ScreenUtil().setWidth(200).toDouble(),
      child: Image.network(Provider.of<CategoryProvider>(context)
          .categoryGoodsList[index]
          .goods_default_icon!),
    );
  }

  //商品名称
  Widget _goodsName(index, context) {
    return Container(
      width: ScreenUtil().setWidth(370).toDouble(),
      padding: const EdgeInsets.all(5),
      child: Text(
        Provider.of<CategoryProvider>(context)
            .categoryGoodsList[index]
            .goods_desc!,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(fontSize: ScreenUtil().setSp(28).toDouble()),
      ),
    );
  }

  //商品价格
  Widget _goodsPrice(index, context) {
    return Container(
      margin: const EdgeInsets.only(top: 20),
      width: ScreenUtil().setWidth(370).toDouble(),
      child: Row(
        children: [
          Text(
            '价格:￥${Provider.of<CategoryProvider>(context).categoryGoodsList[index].goods_default_price!}元',
            style: TextStyle(
                fontSize: ScreenUtil().setSp(23).toDouble(),
                color: Colors.pink),
          ),
          Text(
            '原价:￥${Provider.of<CategoryProvider>(context).categoryGoodsList[index].goods_default_price!}元',
            style: TextStyle(
                fontSize: ScreenUtil().setSp(23).toDouble(),
                color: Colors.black26,
                decoration: TextDecoration.lineThrough),
          )
        ],
      ),
    );
  }

  //构建商品的item
  Widget _listWidgetItem(index, context) {
    return InkWell(
      onTap: () {
        CategoryGoodsListBean goodsListBean =
            Provider.of<CategoryProvider>(context, listen: false)
                .categoryGoodsList[index];
        Provider.of<DetailInfoProvider>(context, listen: false)
            .setGoodsInfo(goodsListBean);
        Application.router!.navigateTo(context, '/detail');
      },
      child: Container(
        padding: const EdgeInsets.only(top: 5, bottom: 5),
        decoration: const BoxDecoration(
            color: Colors.white,
            border:
                Border(bottom: BorderSide(width: 1, color: Colors.black12))),
        child: Row(
          children: [
            _goodsImage(index, context),
            Column(
              children: [
                _goodsName(index, context),
                _goodsPrice(index, context),
              ],
            )
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
        width: ScreenUtil().setWidth(570).toDouble(),
        child: EasyRefresh(
          onRefresh: () async {},
          onLoad: () async {
            _getCategoryGoodsList(
                Provider.of<CategoryProvider>(context, listen: false).childId,
                1,
                Provider.of<CategoryProvider>(context, listen: false).size,
                context);
          },
          header: ClassicalHeader(
              bgColor: Colors.white,
              textColor: Colors.pink,
              infoColor: Colors.pink,
              showInfo: true,
              noMoreText: '',
              infoText: '刷新中...',
              refreshReadyText: '下拉刷新',
              refreshedText: '刷新完成',
              refreshingText: '正在刷新',
              refreshText: '下拉刷新'),
          footer: ClassicalFooter(
              bgColor: Colors.white,
              textColor: Colors.pink,
              infoColor: Colors.pink,
              showInfo: true,
              noMoreText: '',
              loadReadyText: '上拉加载',
              loadedText: '加载完成',
              loadingText: '正在加载',
              loadText: '上拉加载'),
          child: ListView.builder(
            itemBuilder: (context, index) {
              return _listWidgetItem(index, context);
            },
            itemCount:
                Provider.of<CategoryProvider>(context).categoryGoodsList.length,
          ),
        ));
  }
}
